package com.itbaizhan.shopping_order_service.service;

import com.itbaizhan.shopping_common.pojo.CartGoods;
import com.itbaizhan.shopping_common.pojo.Orders;
import com.itbaizhan.shopping_common.service.OrdersService;
import com.itbaizhan.shopping_order_service.mapper.CartGoodsMapper;
import com.itbaizhan.shopping_order_service.mapper.OrdersMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author spf
 * @date 2024/1/19
 * @time 15:38
 */

// 订单服务实现类
@Service
@Component
@Transactional
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartGoodsMapper cartGoodsMapper;
    @Override
    public Orders add(Orders orders) {
        // 设置订单状态为未支付
        if (orders.getStatus() == null){
            orders.setStatus(1);
        }
        // 订单创建时间
        orders.setCreateTime(new Date());
        // 计算金额
        BigDecimal sum = BigDecimal.ZERO;
        List<CartGoods> cartGoods = orders.getCartGoods();
        for (CartGoods cartGood : cartGoods) {
            // 数量
            BigDecimal num = new BigDecimal(cartGood.getNum());
            // 单价
            BigDecimal price = cartGood.getPrice();
            // 总价
            BigDecimal multiply = num.multiply(price);
            sum = sum.add(multiply);
        }
        orders.setPayment(sum);
        // 保存订单
        ordersMapper.insert(orders);
        // 购物车商品保存到数据库中
        for (CartGoods cartGood : cartGoods) {
            cartGood.setOrderId(orders.getId());
            cartGoodsMapper.insert(cartGood);
        }

        return orders;
    }

    // 再支付完成后更新订单表中的数据
    @Override
    public void update(Orders orders) {
        ordersMapper.updateById(orders);
    }

    @Override
    public Orders findById(String id) {
        return ordersMapper.findById(id);
    }

    @Override
    public List<Orders> findUserOrders(Long usrId, Integer status) {
        return ordersMapper.findOrdersByUserIdAndStatus(usrId, status);
    }
}
